package com.kaiyidiannao.activity.auction;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.kaiyidiannao.activity.login_or_registered.LoginOrRegistered;
import com.kaiyidiannao.activity.user_detail.EditUserDetail;
import com.kaiyidiannao.adapter.AuctionAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.waterfall_view.XListView;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.Auction;
import com.kaiyidiannao.model.bean.UserBean;
import com.kaiyidiannao.model.req.model.GetAuctionLIst;
import com.kaiyidiannao.model.req.model.GetAuctionLIstTop;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.AutoTextView;
import com.umeng.common.Log;

import java.util.*;

/**
 * 拍拍乐列表首页
 *
 * @author kTian
 */
public class AuctionActivity extends BaseActionBarActivity implements Observer {

    private AutoTextView mAutoText;

    private XListView waterfallView;
    private List<Auction> mAuctionListData = DataCenter.auctionArrayList;
    private AuctionAdapter mAdapter;

    private int mCategoryId;
    private int mPageNum = 1;

    private ProgressBar mPatProgressBar;

    //最新分类样式
    private CheckBox checkbox_category;//展开分类的checkbox
    private boolean isClose = true;
    private ListView categoryListview;
    private View no_content_view;//没有数据的布局对象
    private SimpleAdapter simpleAdapter;
    private List<Map<String, String>> data;
    private String[] categoryTextArrays = null; //分类数组的对应的文字
    private int preSelectedIndex = 0;

    private ArrayList<UserBean> userBeans = DataCenter.userLogin;
    private ArrayList<UserBean> beans = DataCenter.userBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auction);
        DataCenter.getInstance().addObserver(this);
        DataCenter.rolling_current_module_id = DataCenter.moduleFlag.aution;

        findView();
        initXLIstView();
        initLinstener();
        initData();

        //最新分类
        findActionBar();
        initCategoryData();
        initCategoryView();
        mCategoryId = DataCenter.pat_category_id[0];

        this.showCurrentProgressView();
        if (isLogin()) {

        }
        if (isLogin()) {
            new GetAuctionLIst(getUserid(), mCategoryId).execute();
        } else {
            new GetAuctionLIst(null, mCategoryId).execute();
        }
        new GetAuctionLIstTop(mCategoryId).execute();
        //actionBarView.setTitle(categoryTextArrays[0]);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCenter.auctionTopList.clear();
        DataCenter.getInstance().deleteObserver(this);
    }

    public XListView getmXListView() {
        return waterfallView;
    }

    private void findView() {
        mAutoText = (AutoTextView) findViewById(R.id.txt_auto_pat);
        waterfallView = (XListView) findViewById(R.id.listView_pat);
        categoryListview = (ListView) findViewById(R.id.category_listview);
        mPatProgressBar = (ProgressBar) findViewById(R.id.pat_inner_progress_bar);
        no_content_view = findViewById(R.id.no_content_view);
    }

    private void initXLIstView() {
        waterfallView.setPullLoadEnable(true);
        waterfallView.setPullRefreshEnable(true);
    }

    private void initLinstener() {

        // XListView监听
        ((XListView) waterfallView).setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {
                // 重新刷新此页
                mPageNum = DataCenter.LISTVIEW_DEFAULT_PAGE;
                if (isLogin()) {
                    new GetAuctionLIst(getUserid(), mCategoryId, mPageNum).execute();
                } else {
                    new GetAuctionLIst(null, mCategoryId, mPageNum).execute();
                }
            }

            @Override
            public void onLoadMore() {
                // 加载下一页
                mPageNum++;
                if (isLogin()) {
                    new GetAuctionLIst(getUserid(), mCategoryId, mPageNum).execute();
                } else {
                    new GetAuctionLIst(null, mCategoryId, mPageNum).execute();
                }
            }
        });
        //
        waterfallView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(AuctionActivity.this, AuctionDetailActivity.class);
                intent.putExtra("itemid", mAuctionListData.get(position - 1).getItemid());
                intent.putExtra("catid", mAuctionListData.get(position - 1).getCatid());
                startActivity(intent);
            }

        });
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("分类");
        actionBarView.setTitleOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isClose = !isClose;
                if (isClose) {
                    closeTopBar();
                } else { //开启分类条
                    openTopBar();
                }
            }
        });
        actionBarView.setTitleIconIsUp(false);


        checkbox_category = actionBarView.checkBox;
        checkbox_category.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isShownTopBar()) {
                    closeTopBar();
                } else {
                    openTopBar();
                }
                checkbox_category.setChecked(isShownTopBar());
            }
        });


        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.btn_upload_product));
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userBeans.size() == 0) {
                    Intent intent = new Intent(AuctionActivity.this, LoginOrRegistered.class);
                 //   intent.putExtra("ClassName", AuctionActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(AuctionActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    //finish();
                } else if (beans.get(0).getUsername() == null || beans.get(0).getUsername().equals("")) {
                    Intent intent = new Intent(AuctionActivity.this, EditUserDetail.class);
                   // intent.putExtra("ClassName", AuctionActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(AuctionActivity.this, "请完善您的个人信息", Toast.LENGTH_SHORT).show();
                  //  finish();
                } else {
                    android.util.Log.d("username", beans.get(0).getUserid() + "----------");
                    //  上传商品
                    Intent intent = new Intent(AuctionActivity.this, UploadAuctionActivity.class);
                    startActivity(intent);
                }
            }
        });

    }


    private void initCategoryView() {
        categoryListview = (ListView) findViewById(R.id.category_listview);

        String[] from = new String[]{"img", "title"};
        int[] to = new int[]{R.id.category_icon, R.id.category_title};
        simpleAdapter = new SimpleAdapter(this, data, R.layout.category_listview_item, from, to);
        categoryListview.setAdapter(simpleAdapter);
        categoryListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                simpleAdapter.notifyDataSetChanged();
                actionBarView.setTitle(categoryTextArrays[i]);


                isClose = true;
                closeTopBar();
                // 清理数据
                if (mAuctionListData != null) {
                    mAuctionListData.clear();
                }
                mAdapter.notifyDataSetChanged();
                mCategoryId = DataCenter.pat_category_id[i];
                Log.d("mCategoryId", "");

                mPageNum = DataCenter.LISTVIEW_DEFAULT_PAGE;
                //getNetData();
                showCurrentProgressView();
                if (isLogin()) {
                    new GetAuctionLIst(getUserid(), mCategoryId).execute();
                } else {
                    new GetAuctionLIst(null, mCategoryId).execute();
                }
                new GetAuctionLIstTop(mCategoryId).execute();
            }
        });


    }

    private void initData() {
        mAdapter = new AuctionAdapter(this, mAuctionListData, false);
        waterfallView.setAdapter(mAdapter);
    }

    protected void openTopBar() {
        actionBarView.setTitleIconIsUp(true);
        categoryListview.setVisibility(View.VISIBLE);
        categoryListview.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_in));
    }

    @Override
    protected void closeTopBar() {

        actionBarView.setTitleIconIsUp(false);

        categoryListview.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_out));
        categoryListview.setVisibility(View.GONE);
    }


    @Override
    protected boolean isShownTopBar() {
        return categoryListview.getVisibility() == View.VISIBLE;
    }

    private void initCategoryData() {
        data = new ArrayList<Map<String, String>>();

        TreeMap<String, String> map = null;
        categoryTextArrays = getResources().getStringArray(R.array.patCategory);

        for (int i = 0; i < categoryTextArrays.length; ++i) {
            map = new TreeMap<String, String>();
            if (i == 0) {
                map.put("img", "" + DataCenter.commmon_category_img[0]);
            } else {
                map.put("img", "" + DataCenter.commmon_category_img[1]);
            }
            map.put("title", categoryTextArrays[i] + "...");
            data.add(map);
        }
    }

    /**
     * 此方法不支持缓存
     */
//    @Deprecated
//    private void getNetData() {
//        RequestParams params = new RequestParams();
//        params.put("catid", mCategoryId + "");
//        params.put("page", mPageNum + "");
//        RequestClient.get(AuctionActivity.this, DataCenter.GET_AUCTION_LIST_ADDRESS, params,
//                new AsyncHttpResponseParse(AuctionActivity.this, new LoadDataHandler() {
//
//                    @Override
//                    public void onStart() {
//                        if (mPageNum == 1) {
//                            mPatProgressBar.setVisibility(View.VISIBLE);
//                        }
//                    }
//
//                    @Override
//                    public void onSuccess(String data) {
//                        if (data == null || "".equals(data)) {
//                            return;
//                        }
//                        Gson gson = new Gson();
//                        Type type = new TypeToken<List<Auction>>() {
//                        }.getType();
//                        List<Auction> itemList = gson.fromJson(data, type);
//                        mAuctionListData.addAll(itemList);
//                        mAdapter.notifyDataSetChanged();
//                        gson = null;
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        if (mPageNum == 1) {
//                            mXListView.stopRefresh();
//                            mPatProgressBar.setVisibility(View.GONE);
//                        } else {
//                            mXListView.stopLoadMore();
//                        }
//                    }
//
//                })
//        );
//
//    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            if (isShownTopBar()) {
                actionBarView.checkBox.setChecked(false);

                isClose = true;

                closeTopBar();
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;

        waterfallView.stopLoadMore();
        waterfallView.stopRefresh();
        if (!HttpUtils.isConnected()) {
            mPatProgressBar.setVisibility(View.GONE);
            if (mAuctionListData.size() > 0) {
                no_content_view.setVisibility(View.GONE);
            } else {
                no_content_view.setVisibility(View.VISIBLE);
            }
        }


        if (flag == DataCenter.flag.GET_AUCTION_LIST_TOP_SUCCESS) {
            ArrayList<Auction> targetList = DataCenter.auctionTopList;
            mAutoText.setData3(targetList);
            mAutoText.startRolling();
        }

        if (flag == DataCenter.flag.GET_AUCTION_LIST_SUCCESS) {
            if ((mAuctionListData == null || mAuctionListData.size() < 1)) {
                showCurrentEmptyMsgView(null);
                mAdapter.notifyDataSetInvalidated();
            } else {
                showCurrentDataView();
            }
        }

        if (flag == DataCenter.flag.GET_AUCTION_LIST_FAILED) {
            if (mAuctionListData.size() < 1) {
                showCurrentEmptyMsgView(getText(R.string.listview_msg_error)); //请求失败，请重试
            } else {
                showCurrentDataView();
            }
        }

        mAdapter.notifyDataSetChanged();
    }


    /**
     * 显示列表数据
     */
    private void showCurrentDataView() {
        waterfallView.setVisibility(View.VISIBLE);
        no_content_view.setVisibility(View.GONE);
        mPatProgressBar.setVisibility(View.GONE);
    }

    /**
     * 正在加载，隐藏列表
     */
    private void showCurrentProgressView() {
        waterfallView.setVisibility(View.GONE);
        no_content_view.setVisibility(View.GONE);
        mPatProgressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 提示没有数据或者请求失败
     */
    private void showCurrentEmptyMsgView(CharSequence resStr) {
        waterfallView.setVisibility(View.GONE);
        if (TextUtils.isEmpty(resStr)) {
            resStr = getText(R.string.listview_msg_empty);
        }
        ((TextView) no_content_view.findViewById(R.id.notice_msg_tv)).setText(resStr);
        no_content_view.setVisibility(View.VISIBLE);
        mPatProgressBar.setVisibility(View.GONE);
    }
}
